import { ShelfStudyPlan } from '@/api/Shelf';
import { CoursewaresList } from '@/components/CoursewaresList';
// import { SourceReadySelectModal } from '@/components/SourceReadySelect';
import { SourceSelectModal } from '@/components/SourceSelect';
import { StudyPlanContentEntity } from '@/components/SourceSelect/Entity/interface';
import Source from '@/components/SourceSelect/Entity/Source';
import { getStudyObjectDefaultAll, StudyObjectCheckBoxGroup } from '@/components/StudyObjectSelect';
import { useRequest } from 'ahooks';
import type { UploadFile } from 'antd';
import { App, Button, Card, Empty, Form, Input, InputNumber, Radio, Space } from 'antd';
import { useState } from 'react';
import { useYmAliOss, YmAddPageLayout, YmUpload } from 'ym-design';

export interface AddEditPorps {
  faceImg?: string;
  planName?: string;
  cycleType?: string;
  cycleDay?: number;
  learnObj?: string;
  learnMode?: string;
  planId?: string;
  onBack?(): void;
}

type FormValue = {
  coursewares: Source[][];
  planName: string;
  cycleType: string;
  cycleDay: number;
  learnObj: string;
  learnMode: string;
  faceImg?: UploadFile[];
};

export function AddEdit({ onBack, planId, ...formValue }: AddEditPorps) {
  const [form] = Form.useForm<FormValue>();
  const [modalOpen, setModalOpen] = useState<number>();
  const [initValue] = useState<Partial<FormValue>>(() => {
    if (planId) {
      const { faceImg, ...value } = formValue;
      return { coursewares: [], faceImg: faceImg ? [{ url: faceImg, uid: faceImg, name: '封面' }] : [], ...value };
    } else {
      return {
        cycleType: 'cycle',
        learnMode: 'order',
        cycleDay: 1,
        learnObj: getStudyObjectDefaultAll(),
        coursewares: [],
      };
    }
  });

  useRequest(
    async () => {
      if (planId) {
        return Source.listWithRelationType('learn', planId);
      }
    },
    {
      ready: Boolean(planId),
      onSuccess(data) {
        const result: Source[][] = [];
        data?.reduce((a, b) => {
          const origin = b.origin as StudyPlanContentEntity;
          const aArr = (a[origin.sortNum - 1] ??= []);
          if (origin.coursewareSortNum) {
            aArr[origin.coursewareSortNum - 1] = b;
          } else {
            aArr.push(b);
          }
          return a;
        }, result);
        form.setFieldsValue({ coursewares: result });
      },
    },
  );

  const { run, loading } = useRequest(ShelfStudyPlan.createOrUpdate, {
    manual: true,
    onSuccess() {
      onBack?.();
    },
  });

  const customRequest = useYmAliOss();
  const cycleType = Form.useWatch('cycleType', form);
  const { message } = App.useApp();

  return (
    <YmAddPageLayout
      title={planId ? '编辑计划模版' : '创建计划模版'}
      onBack={onBack}
      items={[
        {
          text: '保存',
          key: 'save',
          loading,
          onClick: async () => {
            const { coursewares: _coursewares, faceImg: _faceImg, ...value } = await form.validateFields();
            let i = 0;
            const params = {
              ...value,
              coursewares: _coursewares.reduce((a, b) => {
                a.push(
                  ...b.map((v, index) => {
                    return {
                      coursewareId: v.id,
                      coursewareSortNum: index + 1,
                      sortNum: i + 1,
                    };
                  }),
                );
                i++;
                return a;
              }, [] as { coursewareId: string; coursewareSortNum: number; sortNum: number }[]),
              faceImg: _faceImg?.map((v) => v.response ?? v.url).join(','),
              planId,
            };
            if (params.coursewares.length === 0) {
              message.error('请选择学习内容');
              return;
            }
            run(params);
          },
          style: {
            width: 295,
          },
        },
      ]}
    >
      <div style={{ height: '100%', overflow: 'auto' }}>
        <Form form={form} labelCol={{ style: { width: 100 } }} preserve initialValues={initValue}>
          <Card title="创建学习计划模版" style={{ marginBottom: 16 }}>
            <Form.Item label="计划名称" name="planName" rules={[{ required: true }]}>
              <Input showCount maxLength={18} placeholder="请填写计划名称"></Input>
            </Form.Item>
            <Form.Item label="类型" required>
              <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
                <Form.Item name="cycleType" noStyle>
                  <Radio.Group>
                    <Radio value="cycle">周期循环</Radio>
                    <Radio value="fixed">固定时间</Radio>
                  </Radio.Group>
                </Form.Item>
                {cycleType !== 'fixed' ? (
                  <div hidden={cycleType !== 'cycle'} style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
                    每
                    <Form.Item name="cycleDay" noStyle rules={[{ required: true, message: '周期循环为空' }]}>
                      <InputNumber max={180} min={1} />
                    </Form.Item>
                    日一学
                  </div>
                ) : null}
              </div>
            </Form.Item>
            <Form.Item label="学习机制" name="learnMode" rules={[{ required: true }]}>
              <Radio.Group>
                <Radio value="order">顺序轮学</Radio>
                <Radio value="polling">随机抽学</Radio>
              </Radio.Group>
            </Form.Item>
            <Form.Item label="学习对象" name="learnObj" rules={[{ required: true, message: '请选择学习对象' }]}>
              <StudyObjectCheckBoxGroup />
            </Form.Item>
            <Form.Item label="封面图">
              <Space size={20}>
                <Form.Item name="faceImg" noStyle rules={YmUpload.formRules(false)}>
                  <YmUpload maxCount={1} cardWidth={375} cardHeight={200} customRequest={customRequest}>
                    请上传封面
                  </YmUpload>
                </Form.Item>
                <div>
                  <p>图片仅支持jpg、png格式 </p>
                  <p> 图片大小750*400 </p>
                </div>
              </Space>
            </Form.Item>
          </Card>
          <Card
            title="选择课件"
            extra={
              <Button
                type="primary"
                shape="round"
                onClick={() => {
                  setModalOpen(Math.random());
                }}
              >
                选择
              </Button>
            }
            bodyStyle={{ display: 'flex', flexDirection: 'column', gap: 20 }}
          >
            <Form.List name="coursewares">
              {(fields = [], { add, remove }) => {
                console.log('fields', fields);
                let render = <Empty image={Empty.PRESENTED_IMAGE_DEFAULT} description="暂未选择任何课件" />;
                if (fields.length) {
                  render = (
                    <>
                      {fields.map(({ name, key }, index) => {
                        // 如果删除到没有课件了,那么就删除掉课件包
                        const getValueFromEvent = (value: Source[]) => {
                          if (!value || value.length === 0) {
                            window.queueMicrotask(() => {
                              remove(index);
                            });
                          }
                          return value;
                        };
                        return (
                          <Card
                            title={'课件包' + (index + 1)}
                            type="inner"
                            key={key}
                            extra={
                              <Button
                                type="text"
                                onClick={() => {
                                  remove(index);
                                }}
                              >
                                删除
                              </Button>
                            }
                          >
                            <Form.Item name={name} noStyle getValueFromEvent={getValueFromEvent}>
                              <CoursewaresList></CoursewaresList>
                            </Form.Item>
                          </Card>
                        );
                      })}
                    </>
                  );
                }

                return (
                  <>
                    {render}
                    <SourceSelectModal
                      openDep={modalOpen}
                      preSet="已上架课件"
                      onChange={(data) => {
                        console.log(data);
                        if (data && data[0].type === '课件包') {
                          Source.listWithRelationType('package', data[0].id).then((data) => {
                            const newdata = JSON.parse(JSON.stringify(data));
                            newdata.map((v: { parentType: string }) => {
                              v.parentType = '课件包';
                            });
                            add(newdata);
                          });
                        } else {
                          add(data);
                        }
                      }}
                    ></SourceSelectModal>
                  </>
                );
              }}
            </Form.List>
          </Card>
        </Form>
      </div>
    </YmAddPageLayout>
  );
}
